package video.background.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import video.background.Controller.ControllerParams.AddNoticeParams;
import video.background.Controller.ControllerParams.HandleNoticeParams;
import video.background.Controller.View.NoticeView;
import video.background.Dao.NoticeDao;
import video.background.Dao.TeamDao;
import video.background.Dao.UserDao;
import video.background.Dao.UserGroupDao;
import video.background.Model.Notice;
import video.background.Model.UserGroup;
import video.background.Model.Users;
import video.background.Utils.DateTimeUtils;
import video.background.Utils.JwtUtils;
import video.background.Utils.MessageUtils;
import video.background.Utils.Result;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: background
 * @description:
 * @author: hlt
 * @create: 2023-08-11 11:37
 **/
@RestController
@RequestMapping("/notices")
@Api(tags = "团队内公告相关接口")
@CrossOrigin(origins = "*", maxAge = 3600)  // 跨域
public class NoticeController {

    @Autowired
    private UserGroupDao userGroupDao;

    @Autowired
    private NoticeDao noticeDao;
    @Autowired
    private UserDao userDao;

    @Autowired
    private TeamDao teamDao;

    @GetMapping("/getNoticesInGroup")
    @ApiOperation("成员获取团队内的公告列表")
    public Result getNoticesInGroup(@RequestHeader String Authorization,
                                    @RequestParam Long groupId,
                                    @RequestParam(name = "currentPage", required = false, defaultValue = "1") Long currentPage,
                                    @RequestParam(name = "pageSize", required = false, defaultValue = "10") Long pageSize){
        Long userId = JwtUtils.decoderToken(Authorization);
        LambdaQueryWrapper<UserGroup> uglqw = new LambdaQueryWrapper<>();
        uglqw.eq(UserGroup::getUserId, userId).eq(UserGroup::getGroupId, groupId);
        UserGroup userGroup = userGroupDao.selectOne(uglqw);
        if(userGroup == null) return Result.Error("权限不足！", null);
        LambdaQueryWrapper<Notice> nlqw = new LambdaQueryWrapper<>();
        nlqw.eq(Notice::getGroupId, groupId);
        List<Notice> notices = noticeDao.selectList(nlqw);
        List<NoticeView> noticeViews = notices.stream().map(notice -> {
            NoticeView noticeView = new NoticeView();
            BeanUtils.copyProperties(notice, noticeView);
            // 防止用户注销的隐患
            Users users = userDao.selectById(notice.getUserId());
            if(users == null) noticeView.setUserName("用户已注销!");
            else noticeView.setUserName(users.getUserName());
            noticeView.setGroupTitle(teamDao.selectById(notice.getGroupId()).getGroupName());
            return noticeView;
        }).collect(Collectors.toList());
        Page<NoticeView> page = new Page<>(currentPage,pageSize);
        int count = noticeViews.size();
        page.setRecords(noticeViews);
        page.setPages(count % pageSize == 0 ? currentPage / pageSize : currentPage / pageSize + 1);
        page.setTotal(count);
        return Result.Success("请求成功！", page);
    }

    @PostMapping("/addNotice")
    @ApiOperation("管理员新增公告的接口")
    public Result addNotice(@RequestHeader String Authorization, @RequestBody AddNoticeParams data){
        String content = data.getContent();
        Long groupId = data.getGroupId();
        String noticeTitle = data.getNoticeTitle();
        Long userId = JwtUtils.decoderToken(Authorization);
        if(content == null || groupId == null || noticeTitle == null || userId == null
        || content.equals("") || noticeTitle.equals(""))
            return Result.Error("数据不全！",null);
        LambdaQueryWrapper<UserGroup> uglqw = new LambdaQueryWrapper<>();
        uglqw.eq(UserGroup::getUserId, userId).eq(UserGroup::getGroupId, groupId);
        UserGroup userGroup = userGroupDao.selectOne(uglqw);
        if(userGroup == null || userGroup.getUserRole() == '2') return Result.Error("权限不足！", null);
        Notice notice = new Notice();
        BeanUtils.copyProperties(data, notice);
        String currentDate = DateTimeUtils.dateTimeToString();
        notice.setCreateTime(currentDate);
        notice.setUpdateTime(currentDate);
        notice.setUserId(userId);
        notice.setGroupId(groupId.toString());
        noticeDao.insert(notice);
        return Result.Success("发布成功！", null);
    }

    @ApiOperation("管理员修改公告的接口")
    @PostMapping("/updateNotice")
    public Result updateNotice(@RequestHeader String Authorization, @RequestBody NoticeView data){
        Long userId = 0l;
        try {
            userId = JwtUtils.decoderToken(Authorization);
        } catch (Exception e) {
            return Result.Error("token有误！", null);
        }
        if(userId == 0l) return Result.Error("数据不全！", null);
        String groupId = data.getGroupId();
        LambdaQueryWrapper<UserGroup> uglqw = new LambdaQueryWrapper<>();
        uglqw.eq(UserGroup::getGroupId,groupId).eq(UserGroup::getUserId,userId);
        if(userGroupDao.selectOne(uglqw).getUserRole()  == '2') return Result.Error("权限不足！", null);
        Long noticeId = data.getNoticeId();
        Notice notice = new Notice();
        BeanUtils.copyProperties(data, notice);
        noticeDao.updateById(notice);
        return Result.Success("修改成功！", null);
    }

    @ApiOperation("管理员删除公告的接口")
    @PostMapping("/deleteNotice")
    public Result deleteNotice(@RequestHeader String Authorization, @RequestBody HandleNoticeParams data){
        Long userId = 0l;
        try {
            userId = JwtUtils.decoderToken(Authorization);
        } catch (Exception e) {
            return Result.Error("token有误！", null);
        }
        if(userId == 0l) return Result.Error("数据不全！", null);
        Long groupId = data.getGroupId();
        if(groupId == null) return Result.Error("数据不全！",null);
        LambdaQueryWrapper<UserGroup> uglqw = new LambdaQueryWrapper<>();
        uglqw.eq(UserGroup::getGroupId,groupId).eq(UserGroup::getUserId,userId);
        if(userGroupDao.selectOne(uglqw).getUserRole()  == '2') return Result.Error("权限不足！", null);
        Long noticeId = data.getNoticeId();
        noticeDao.deleteById(noticeId);
        return Result.Success("删除成功！", null);
    }
}
